package chat;

import java.io.*;
import java.net.*;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

public class ChatServer {
    private static final int PORT = 12345;
    // 使用线程安全的Map来存储客户端输出流和IP地址
    private static ConcurrentHashMap<PrintWriter, String> clientInfoMap = new ConcurrentHashMap<>();

    public static void main(String[] args) {
        System.out.println("聊天服务器正在启动...");
        try (ServerSocket serverSocket = new ServerSocket(PORT)) {
            System.out.println("服务器已启动，等待客户端连接...");
            while (true) {
                new ClientHandler(serverSocket.accept()).start();
            }
        } catch (IOException e) {
            System.err.println("服务器异常: " + e.getMessage());
        }
    }

    private static class ClientHandler extends Thread {
        private Socket socket;
        private PrintWriter out;
        private BufferedReader in;
        private String clientIP;

        public ClientHandler(Socket socket) {
            this.socket = socket;
            this.clientIP = socket.getInetAddress().getHostAddress();
        }

        public void run() {
            try {
                in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                out = new PrintWriter(socket.getOutputStream(), true);

                // 将客户端信息存入Map
                clientInfoMap.put(out, clientIP);
                System.out.println("客户端连接 - IP: " + clientIP + ", 总数: " + clientInfoMap.size());

                // 广播新用户加入消息
                broadcast("系统消息: 用户 [" + clientIP + "] 加入了聊天室", true);

                String message;
                while ((message = in.readLine()) != null) {
                    System.out.println("收到来自 " + clientIP + " 的消息: " + message);
                    broadcast("[" + clientIP + "] " + message, false);
                }
            } catch (IOException e) {
                System.err.println("客户端(" + clientIP + ")处理异常: " + e.getMessage());
            } finally {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                // 移除客户端信息
                clientInfoMap.remove(out);
                System.out.println("客户端断开 - IP: " + clientIP + ", 剩余: " + clientInfoMap.size());
                broadcast("系统消息: 用户 [" + clientIP + "] 离开了聊天室", true);
            }
        }
    }

    /**
     * 广播消息给所有客户端
     * @param message 要广播的消息
     * @param isSystemMsg 是否是系统消息（系统消息会显示IP但不显示用户名前缀）
     */
    private static void broadcast(String message, boolean isSystemMsg) {
        for (PrintWriter writer : clientInfoMap.keySet()) {
            writer.println(message);
        }
    }
}